package com.itheima.filter;

import com.itheima.controller.DeptController;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.LoggerFactory;

import java.io.IOException;
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(DeptController.class);

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        // 1.获取请求url。
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        String uri = req.getRequestURI();
        StringBuffer url = req.getRequestURL();
        log.info("请求的url是：{}", url);
        log.info("请求的uri是：{}", uri);

        // 2.判断请求url中是否包含login，如果包含，说明是登录操作，放行。
        if (uri.contains("login")) {
            // 放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 3.获取请求头中的令牌（token）。
        String token = req.getHeader("token");

        // 4.判断令牌是否存在，如果不存在，响应401。
        if (token == null) {
            resp.setStatus(401);
            log.info("令牌为空！");
            return;
        }

        // 5.解析token，如果解析失败，响应401 。
        try {
            Claims claims = JwtUtils.parseJWT(token);
            log.info("解析的token是：{}", claims);
        } catch (Exception e) {
            resp.setStatus(401);
            log.info("令牌解析失败！{}", token);
            return;
        }

        // 6.放行。
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
